import re
import uuid

from redis.client import Redis

mconn = Redis(host="192.168.35.110", port=6379, db=0, decode_responses=True)


def index_job(conn, job_id, skills):
    pipline = conn.pipeline(True)
    for skill in skills:
        pipline.sadd('idx:skill:' + skill, job_id)
    pipline.zadd('idx:jobs:req', {job_id: len(set(skills))})
    pipline.execute()


def _zset_common(conn, method, scores, ttl=30, **kw):
    id = str(uuid.uuid4())
    execute = kw.pop('_execute', True)
    pipe = conn.pipeline(True) if execute else conn
    for key in list(scores.keys()):
        scores['idx:' + key] = scores.pop(key)
    getattr(pipe, method)('idx:' + id, scores, **kw)
    pipe.expire('idx：' + id, ttl)
    if execute:
        pipe.execute()
    return id


def zintersect(conn, items, ttl=30, **kw):
    return _zset_common(conn, 'zinterstore', dict(items), ttl, **kw)


def zunion(conn, items, ttl=30, **kw):
    return _zset_common(conn, 'zunionstore', dict(items), ttl, **kw)


def find_jobs(conn, candidate_skills, ttl=300):
    skills = {}
    for skill in candidate_skills:
        skills['skill:' + skill] = 1
    job_scores = zunion(conn, skills, ttl)
    final_result = zintersect(conn, {job_scores: -1, 'jobs:req': 1})
    return conn.zrangebyscore('idx:' + final_result, 0, 0)


def print_hi(name):
    # 在下面的代码行中使用断点来调试脚本。
    print(f'Hi, {name}')  # 按 Ctrl+F8 切换断点。


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    index_job(mconn, '123', {'ea', 'java', 'python', 'redis'})
    index_job(mconn, '456', {'postgresql'})
    index_job(mconn, '789', {'java', 'mysql', 'ea', 'python', 'redis', 'influxdb'})
    print(find_jobs(mconn, {'java', 'mysql', 'ea', 'python', 'redis'}))
    print_hi('PyCharm')

# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助
